package com.jiubanqingchen.future.org.admin;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jiubanqingchen.future.common.tool.RecordTool;
import com.jiubanqingchen.future.common.tool.SqlTool;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.annotation.Sqlkey;

import java.util.List;

public class BaseService implements IBaseService {

    @Override
    public void delete(String tableName, String field, Object fieldValue, User _usr) {
        Db.template("common.delete_where",
                Kv.by("tableName", tableName).set("field", field).set("fieldValue", fieldValue)).update();
    }

    @Override
    public <T> List<T> exportData(Kv kv) throws Exception {
        return null;
    }

    @Override
    public <T> List<T> exportData(String sqlKey, Kv kv, Class<T> clazz) throws Exception {
        return RecordTool.recordListToBeanList(Db.template(sqlKey, kv).find(), clazz);
    }

    @Override
    public List<Record> list(Kv kv) throws Exception {
        return Db.template(getSqlKey(), kv).find();
    }

    @Override
    public List<Record> list(String sqlKey, Kv kv) throws Exception {
        return Db.template(sqlKey, kv).find();
    }

    @Override
    public List<Record> list(String sqlKey, Object... params) throws Exception {
        return Db.template(sqlKey, params).find();
    }

    @Override
    public Record id(String id, Kv kv) throws Exception {
        return this.id(getSqlKey(), id, kv);
    }

    @Override
    public Record id(String sqlKey, String id, Kv kv) throws Exception {
        if (id == null) throw new Exception("id 不能为空");
        return Db.template(sqlKey, kv.set("id", id)).findFirst();
    }

    @Override
    public Page<Record> page(int pageNum, int limit, Kv kv) throws Exception {
        return this.page(getSqlKey(), pageNum, limit, kv);
    }

    @Override
    public Page<Record> page(String sqlKey, int pageNum, int limit, Kv kv) throws Exception {
        SqlTool.orderHandle(kv);//处理orderby
        Page<Record> page = Db.template(sqlKey, kv).paginate(pageNum, limit);
        SqlTool.hideColumnsTool(page.getList(), kv.getStr("hideColumns"));//隐藏某些列数据
        return page;
    }

    /**
     * 得到当前service的sqlkey
     *
     * @return
     */
    public String getSqlKey() throws Exception {
        if (this.getClass().isAnnotationPresent(Sqlkey.class)) {
            return this.getClass().getAnnotation(Sqlkey.class).value();
        }
        throw new Exception("sqlKey不能为空");
    }
}
